import cv2
import numpy as np
import pymysql
import configparser
import sys
import threading
# 获取配置
cfg = configparser.ConfigParser()
cfg.read("config.ini")
class DealImage (threading.Thread):
    def __init__(self,threadID=1 ,name = "",img = None,db = None):
        threading.Thread.__init__(self)
        # 获取配置
        self.threadID = threadID
        self.config = cfg
        self.name = name
        self.img = img
        self.thread_num = self.config.get("sys", "thread_num")
        self.db = db
        self.db_cursor = db.cursor()
        print(str(db))
    # 获取轮廓
    def get__contour(self):
        print("处理中...")
        img = self.img
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        height = img.shape[0]
        width = img.shape[1]
        channels = img.shape[2]
        x = cv2.Sobel(gray, cv2.CV_16S, 1, 0)
        absX = cv2.convertScaleAbs(x)  # 转回uint8
        y = cv2.Sobel(gray, cv2.CV_16S, 0, 1)
        absY = cv2.convertScaleAbs(y)  # 转回uint8
        dst = cv2.addWeighted(absX, 0.5, absY, 0.5, 0)
        low = 0
        high = 0
        if self.threadID == int(self.thread_num)-1:
            low = height // int(self.thread_num) * (self.threadID)
            high = height
        else:
            low = height // int(self.thread_num) * self.threadID
            high = height // int(self.thread_num) * (self.threadID + 1)
        list = []
        for row in range(int(low),int(high)):
            for col in range(width):
                pv = dst[row, col]
                dst[row, col] = 255 - pv

                # 保存图片RPG信息
                list_data = [self.name, str(row), str(col),str(pv)]
                list.append(list_data)
        #保存图片信息
        print("数据导入中...")
        rbg_sql = '''INSERT INTO ima_rbg(name,x,y,z) VALUES(%s,%s,%s,%s)'''
        self.db_cursor.executemany(rbg_sql, list)
        replace_data = (self.name, width, height)
        replace_sql = '''INSERT INTO ima_info(name,width,height) VALUES(%s,%s,%s)'''
        self.db_cursor.execute(replace_sql, replace_data)
        self.db.commit()
        print("数据导入完成")
        cv2.imshow("Ima", dst)
        print("处理完成。")
        k = cv2.waitKey(0)
        if k == 27:
            cv2.destroyAllWindows()
            sys.exit()

    def run(self):
        print(str(self.threadID) + " is running")
        self.get__contour()

#按路径读取图片
def cv_imread(filePath=""):
    cv_img=cv2.imdecode(np.fromfile(filePath,dtype=np.uint8),-1)
    return cv_img

#获取数据库连接
def get_db(config = None):
    try:
        db_host = config.get("db", "host")
        db_port = int(config.get("db", "port"))
        db_user = config.get("db", "user")
        db_pass = config.get("db", "password")
        db_db = config.get("db", "db")
        db_charset = config.get("db", "charset")
        db = pymysql.connect(host=db_host, port=db_port, user=db_user, passwd=db_pass, db=db_db,
                                  charset=db_charset)
        return db
    except Exception as err:
        print("请检查数据库配置")
        sys.exit()

if __name__ == '__main__':
    threads = []
    threads_num = int(cfg.get("sys", "thread_num"))
    img = cv_imread("E:\\外观质检\\胎侧挂伤\\合格品.jpg")
    # img = cv_imread("E:\\Aiyou\\bg.jpg")
    for i in range(0, threads_num):
        m = DealImage(i, "bg",img,get_db(cfg))
        threads.append(m)

    for i in range(0, threads_num):
        threads[i].start()

    for i in range(0, threads_num):
        threads[i].join()
